import _ from 'lodash'
import fs from 'fs'

export class ConfigManager {
  constructor(configPath = './config.json') {
    this.configPath = configPath
    this.config = this.loadConfig(configPath)
    this.mergeEnvVars()
  }
  
  loadConfig(path) {
    try {
      const text = fs.readFileSync(path, 'utf8')
      return JSON.parse(text)
    } catch (err) {
      console.error('Failed to load config:', err)
      return {}
    }
  }
  
  mergeEnvVars() {
    const envMappings = {
      'PORT': 'base.port',
      'RDB_URL': 'biz.rdb.proxyUrl',
      'RDB_TYPE': 'biz.rdb.type',
      'BSS_HOST': 'biz.bss.host',
      'BSS_PORT': 'biz.bss.port',
      'ORACLE_URL': 'biz.oracle.proxyUrl'
    }
    
    _(envMappings).forEach((configPath, envKey) => {
      if (process.env[envKey]) {
        _.set(this.config, configPath, process.env[envKey])
      }
    })
  }
  
  get(path, defaultValue) {
    return _.get(this.config, path, defaultValue)
  }
  
  set(path, value) {
    _.set(this.config, path, value)
  }
  
  getAll() {
    return this.config
  }
  
  getBiz() {
    return this.config.biz || {}
  }
  
  getTasks() {
    return this.get('biz.tasks', {})
  }
  
  getProxy() {
    return this.config.proxy || {}
  }
}